from django import forms
from django.core.exceptions import ValidationError

from web import models
from web.forms.base_form import BaseForm
from web.forms.widgets import ColorRadioSelect


class ProjectForm(BaseForm, forms.ModelForm):
    # desc = forms.CharField(widget=forms.Textarea())
    # color不应用BaseForm中__init__方法初始化color字段
    base_class_exclude = ['color']

    class Meta:
        model = models.Project
        fields = ["name", "color", "desc"]
        widgets = {
            "desc": forms.Textarea,
            # color不应用BaseForm中__init__方法初始化color字段
            # "color": forms.RadioSelect,
            "color": ColorRadioSelect(attrs={"class": "color-radio"}),
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        # 重复创建项目
        name = self.cleaned_data['name']
        exist = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exist:
            raise ValidationError("此项目已创建过，不能重复创建")

        # 项目额度不足
        # 已创建项目数量
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError("项目额度已用完，请购买套餐")

        return name